import { Byte } from '../../api/io/Byte';
import { ArenaRankPlayer } from './ArenaRankPlayer';
import { ITimer } from '../../api/timer/ITimer';
import { IAsync } from '../../api/event/IAsync';



/**竞技场历史玩家信息属性枚举*/
export const enum E_ArenaRecordPlayer {
	/**基础信息*/
	PLAYER = 0,
	/**积分变化量*/
	ARENA_SCORE_UPDATE = 1,
	/**排名变化量*/
	RANK_INDEX_UPDATE = 2,
	/**枚举数量*/
	EnumCount = 3
}


/**竞技场历史玩家信息*/
export class ArenaRecordPlayer {
	/**事件ID*/
	public static readonly EVENT_ID = 'STRUCT_DATA_ARENA_RECORD_PLAYER_EVENT_ID';
	/**整体更新事件ID（部分只需要监听整体变化）*/
	public static readonly TOTAL_EVENT_ID = 'STRUCT_DATA_ARENA_RECORD_PLAYER_TOTAL_EVENT_ID';
	/**缓存池*/
	private static POOL: ArenaRecordPlayer[] = [];

	/**创建入口*/
	public static create(json?: string): ArenaRecordPlayer {
		const c = this.POOL.pop() || new ArenaRecordPlayer();
		c._destroyed = false;
		c.resetProperty();
		if (json) {
			c.parse(json);
		}
		return c;
	}


	/**已释放*/
	protected _destroyed = false;
	/**基础信息*/
	protected _player: ArenaRankPlayer = null;
	/**积分变化量 (int32)*/
	protected _arenaScoreUpdate: number;
	/**排名变化量 (int16)*/
	protected _rankIndexUpdate: number;


	/**构建函数-私有，防止外部创建*/
	private constructor() {
	}


	/**释放*/
	public destroy(): void {
		if (this._destroyed) {
			return;
		}
		this._destroyed = true;
		this.resetProperty(true);
		if (ArenaRecordPlayer.POOL.indexOf(this) === -1) {
			ArenaRecordPlayer.POOL.push(this);
		}
	}

	/**基础信息*/
	public get player() {
		return this._player;
	}


	/**积分变化量*/
	public get arenaScoreUpdate() {
		return this._arenaScoreUpdate;
	}


	/**积分变化量*/
	public set arenaScoreUpdate(v: number) {
		this._arenaScoreUpdate = v;
	}


	/**排名变化量*/
	public get rankIndexUpdate() {
		return this._rankIndexUpdate;
	}


	/**排名变化量*/
	public set rankIndexUpdate(v: number) {
		this._rankIndexUpdate = v;
	}



	/**通过枚举获取值*/
	public getV(k: E_ArenaRecordPlayer): any {
		switch (k) {
			case E_ArenaRecordPlayer.PLAYER: return this._player;
			case E_ArenaRecordPlayer.ARENA_SCORE_UPDATE: return this._arenaScoreUpdate;
			case E_ArenaRecordPlayer.RANK_INDEX_UPDATE: return this._rankIndexUpdate;
			default: return null;
		}
	}


	/**通过枚举设置值*/
	public setV(k: E_ArenaRecordPlayer, v: any): void {
		switch (k) {
			case E_ArenaRecordPlayer.PLAYER: this._player = v; break;
			case E_ArenaRecordPlayer.ARENA_SCORE_UPDATE: this._arenaScoreUpdate = v; break;
			case E_ArenaRecordPlayer.RANK_INDEX_UPDATE: this._rankIndexUpdate = v; break;
			default: break;
		}
	}


	/**初始化*/
	public resetProperty(fromDestroy = false): void {
		//基础信息
		if (this._player) {
			this._player.destroy();
			this._player = null;
		}
		if (!fromDestroy) {
			this._player = ArenaRankPlayer.create();
		}
		//积分变化量
		this._arenaScoreUpdate = 0;
		//排名变化量
		this._rankIndexUpdate = 0;
	}


	/**序列化*/
	public stringify(toString: boolean): string | any {
		const json: any = {};
		if (this._player) {
			json.player = this._player.stringify(false);
		}
		if (this._arenaScoreUpdate) {
			json.arenaScoreUpdate = this._arenaScoreUpdate;
		}
		if (this._rankIndexUpdate) {
			json.rankIndexUpdate = this._rankIndexUpdate;
		}

		return toString ? JSON.stringify(json) : json;
	}


	/**反序列化*/
	public parse(jsonv: string | any): this {
		this.resetProperty();
		if (!jsonv) {
			return this;
		}
		const json = typeof (jsonv) === 'string' ? JSON.parse(jsonv) : jsonv;
		if (json.player) {
			this._player.destroy();
			this._player = ArenaRankPlayer.create(json.player);
		}
		if (json.arenaScoreUpdate) {
			this._arenaScoreUpdate = json.arenaScoreUpdate;
		}
		if (json.rankIndexUpdate) {
			this._rankIndexUpdate = json.rankIndexUpdate;
		}
		return this;
	}


	/**序列化-二进制*/
	public toBytes(byte: Byte): void {
		if (!byte) {
			return;
		}
		this._player.toBytes(byte);
		byte.writeInt32(this._arenaScoreUpdate);
		byte.writeInt16(this._rankIndexUpdate);
	}


	/**反序列化-二进制*/
	public fromBytes(byte: Byte): this {
		this.resetProperty();
		if (!byte) {
			return;
		}
		this._player.fromBytes(byte);
		this._arenaScoreUpdate = byte.readInt32();
		this._rankIndexUpdate = byte.readInt16();
		return this;
	}


	/**克隆*/
	public clone(): ArenaRecordPlayer {
		const byte = Byte.createFromPool();
		this.toBytes(byte);
		byte.pos = 0;
		const clonev = ArenaRecordPlayer.create().fromBytes(byte);
		Byte.recoverToPool(byte);
		return clonev;
	}


	/**处理更新*/
	public processUpdate(jsonv: string): void {
		if (!jsonv) {
			return;
		}

		const eventID = ArenaRecordPlayer.EVENT_ID;
		const us = JSON.parse(jsonv);

		for (let i = 0, len = us.length; i < len;) {
			const idx = us[i];
			//基础信息
			if (idx === E_ArenaRecordPlayer.PLAYER) {
				const fui: string = us[i + 1];
				if (this._player) {
					this._player.processUpdate(fui);
				}
				else {
					console.error('ArenaRecordPlayer player is null when update.');
				}
				IAsync.dispatch(eventID, idx);
				i += 2;
				continue;
			}
			//积分变化量
			if (idx === E_ArenaRecordPlayer.ARENA_SCORE_UPDATE) {
				const oldv = this._arenaScoreUpdate;
				this._arenaScoreUpdate = us[i + 1];
				IAsync.dispatch(eventID, idx, this._arenaScoreUpdate, oldv);
				i += 2;
				continue;
			}
			//排名变化量
			if (idx === E_ArenaRecordPlayer.RANK_INDEX_UPDATE) {
				const oldv = this._rankIndexUpdate;
				this._rankIndexUpdate = us[i + 1];
				IAsync.dispatch(eventID, idx, this._rankIndexUpdate, oldv);
				i += 2;
				continue;
			}

			console.error('[Struct Data] can not find enum in ArenaRecordPlayer with idx = ' + idx + ', version maybe wrong.')
		}

		//全更事件
		ITimer.callLater(this, this.dispatchTotalUpdate);
	}


	/**比对不一致结果*/
	public getCompareInfo(other: ArenaRecordPlayer): string {
		if (!other) {
			return null;
		}

		const updates: any[] = [];

		//基础信息
		{
			const ui = this._player.getCompareInfo(other._player);
			if (ui && ui.length > 0) {
				updates.push(E_ArenaRecordPlayer.PLAYER, ui);
			}
		}
		if (this._arenaScoreUpdate !== other._arenaScoreUpdate) {
			updates.push(E_ArenaRecordPlayer.ARENA_SCORE_UPDATE, this._arenaScoreUpdate);
		}
		if (this._rankIndexUpdate !== other._rankIndexUpdate) {
			updates.push(E_ArenaRecordPlayer.RANK_INDEX_UPDATE, this._rankIndexUpdate);
		}

		const jsonv = updates.length === 0 ? null : JSON.stringify(updates);
		return jsonv;
	}


	/**全部更新*/
	protected dispatchTotalUpdate(): void {
		IAsync.dispatch(ArenaRecordPlayer.TOTAL_EVENT_ID, this.getV(0));
	}

}
